package cn.rui.service;

import cn.hutool.core.date.DateUtil;
import cn.rui.common.ContentBean;
import cn.rui.common.ResponseBean;
import cn.rui.mapper.LoginLogMapper;
import cn.rui.mapper.UserMapper;
import cn.rui.pojo.LoginLog;
import cn.rui.pojo.User;
import cn.rui.pojo.vo.PageVo;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpSession;
import java.util.Date;
import java.util.List;

/**
 * @author 徽州大都督
 * @date 2021/6/8
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class LoginLogService {

    @Autowired
    private LoginLogMapper loginLogMapper;

    @Autowired
    private UserMapper userMapper;


    public ResponseBean findPage(PageVo pageVo, HttpSession session) {
        Page<LoginLog> page = new Page<> (pageVo.getCurrentPage (), pageVo.getPageSize ());
        QueryWrapper<LoginLog> wrapper = new QueryWrapper<> ();

        if (pageVo.getLoginStatus () != null && pageVo.getLoginStatus () == 1) {
            wrapper.eq ("login_status", 1);
        } else if (pageVo.getLoginStatus () != null && pageVo.getLoginStatus () == 0) {
            wrapper.eq ("login_status", 0);
        }

        List<String> dateTime = pageVo.getDateTime ();

        if (dateTime != null && dateTime.size () > 0) {
            Date startTime = DateUtil.parse (dateTime.get (0));
            Date endTime = DateUtil.parse (dateTime.get (1));
            wrapper.between ("login_time", startTime, endTime);
        }

        wrapper.orderByDesc ("login_time");

        IPage<LoginLog> loginLogIPage = loginLogMapper.selectPage (page, wrapper);

        PageVo vo = new PageVo ();
        vo.setTotal (loginLogIPage.getTotal ());
        vo.setCurrentPage (pageVo.getCurrentPage ());

        List<LoginLog> loginLogList = loginLogIPage.getRecords ();
        for (LoginLog loginLog : loginLogList) {
            User user = userMapper.selectById (loginLog.getUserId ());
            loginLog.setUser (user);
        }

        vo.setData (loginLogList);

        return ResponseBean.success (ContentBean.QuerySuccess, vo);
    }

    public ResponseBean deleteById(Integer id) {
        loginLogMapper.deleteById (id);

        return ResponseBean.success (ContentBean.DeleteSuccess);
    }
}
